package com.imy.rootserver.screen;

import android.util.Log;

import androidx.test.uiautomator.UiDevice;

import com.imy.rootserver.socket.SocketTransceiver;
import com.imy.rootserver.socket.TcpServer;
import com.imy.rootserver.utils.ProtocolCreate;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ScreenHandler {
    private UiDevice mUiDevice;
    private TcpServer mTcpServer;
    private ExecutorService executorService;
    public ScreenHandler(UiDevice uiDevice, TcpServer server) {
        this.mUiDevice = uiDevice;
        this.mTcpServer = server;
        executorService = Executors.newSingleThreadExecutor();
    }

    public void screen(final String path) {
        //提升一下权限
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String localPath ="/data/local/tmp";
                    String s = mUiDevice.executeShellCommand("chmod 777 -R " + localPath);
                    String filePath =localPath+"/screen.png";
                    Log.i("TouchServer", "executeShellCommand screen :" + s);
                    File file = new File(filePath);
                    if (file.exists()){
                        file.delete();
                    }
                    boolean b = mUiDevice.takeScreenshot(file, 1.0f, 100);
                    List<SocketTransceiver> clients = mTcpServer.getClients();
                    for (int i = 0; i < clients.size(); i++) {
                        String screen = ProtocolCreate.createScreen(path, b,filePath);
                        clients.get(i).send(screen);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
